from PIL import Image, ImageDraw, ImageFont
import random
from io import BytesIO
from django.shortcuts import HttpResponse

def get_valid_img(request):
    """
    基于PIL模块动态获取验证码
    :param request:
    :return:
    """

    # 随机获取RGB的三个值
    def get_random_color():

        return (random.randint(0,255),random.randint(0,255),random.randint(0,255))

    # 生成一张图片
    img = Image.new("RGB", (350, 38), get_random_color())
    # 画图
    draw = ImageDraw.Draw(img)
    # 字体
    font = ImageFont.truetype("static/fonts/kumo.ttf", 32)

    keep_str = ""
    for i in range(6):
        random_num = str(random.randint(0, 9))  # 生成数字
        random_lowalf = chr(random.randint(97, 122))    # 生成小写字母
        random_upperalf = chr(random.randint(65, 90))   # 生成大写字母
        random_char = random.choice([random_num, random_lowalf, random_upperalf])
        draw.text((i * 30 + 50, 0), random_char, get_random_color(), font=font)
        keep_str += random_char

    # 写与读
    f = BytesIO()   # 一个内存句柄
    img.save(f, "png")
    data = f.getvalue()

    print('keep_str：', keep_str)


    # 将验证码存在各自的session中

    request.session['keep_str'] = keep_str

    return HttpResponse(data)